package com.lujieni.netty.c5;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.net.InetSocketAddress;
import java.util.Random;
import java.util.Scanner;

public class HelloWorldClient {
    public static void main(String[] args) throws InterruptedException {
       ha();
    }

    private static byte[] fill10Bytes(byte b){
        Random r = new Random();
        int n = r.nextInt(10);
        byte[] bb = new byte[10];
        for (int i = 0; i < 10; i++) {
            if(i < n){
                bb[i] = b;
            }else{
                bb[i] = '-';
            }
        }
        return bb;
    }

    private static StringBuilder makeString(char c, int length){
        StringBuilder sb = new StringBuilder(length + 1);
        for (int i = 0; i < length; i++) {
            sb.append(c);
        }
        sb.append("\n");
        return sb;
    }

    private static void ha() {
        NioEventLoopGroup ne = new NioEventLoopGroup();
        try {
            ChannelFuture cf = new Bootstrap()
                    .group(ne)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        // 在连接建立后被调用,仅仅是加了处理器而已
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {

                            ch.pipeline().addLast(new LengthFieldPrepender(4));

                            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                                @Override
                                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                    for (int i = 0; i < 10; i++) {
                                        ByteBuf buffer = ctx.alloc().buffer();
                                        buffer.writeBytes(new User("lujieni", 18).toString().getBytes());
                                        ctx.writeAndFlush(buffer);
                                    }
                                }
                            });
                            ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        }
                    })
                    // 异步阻塞 真正执行连接的是NioEventLoopGroup中的eventLoop
                    .connect(new InetSocketAddress("localhost", 8081));
            cf.sync(); // 阻塞当前线程知道nio线程建立完连接
            cf.channel().closeFuture().sync();
        } catch (InterruptedException e) {
        } finally {
            ne.shutdownGracefully();
        }
    }
}

class User{

    private String name;
    private Integer age;

    public User(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}